package net.app.zoneland.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.app.zoneland.common.core.vo.PageResult;
import net.app.zoneland.common.core.vo.Result;
import net.app.zoneland.domain.SysMenu;
import net.app.zoneland.domain.SysRole;
import net.app.zoneland.dto.MenuDTO;
import net.app.zoneland.platform.service.ISysMenuService;
import net.app.zoneland.platform.service.ISysRoleMenuService;
import net.app.zoneland.platform.service.ISysRoleService;
import net.app.zoneland.vo.AuthTreeVo;
import net.app.zoneland.vo.MenuTreeVo;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author LENOVO
 * @CreateTime 2021/1/8 14:56
 * @Version: 1.0
 */
@Api(tags = "角色接口")
@RestController
@RequestMapping("/roles")
@Slf4j
@AllArgsConstructor
public class SysRoleController {

    private final ISysRoleService sysRoleService;

    private final ISysRoleMenuService sysRoleMenuService;

    private final ISysMenuService sysMenuService;

    @ApiOperation(value="角色列表分页", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name="page",value="页面",paramType = "query",dataType = "Integer"),
            @ApiImplicitParam(name="limit", value = "每页数量",paramType = "query",dataType = "Integer"),
            @ApiImplicitParam(name="role",value = "角色信息",paramType = "query",dataType = "SysRole")
    })
    @GetMapping("/index")
    public Result index(Integer page, Integer limit, SysRole role){
        IPage<SysRole> result = sysRoleService.list(new Page<>(page, limit), role);
       return PageResult.success(result.getRecords(),result.getTotal());
    }

    @ApiOperation(value="角色列表", httpMethod = "GET")
    @ApiImplicitParam(name="role",value = "角色信息",paramType = "query",dataType = "SysRole")
    @GetMapping("/roleIndex")
    public Result roleIndex(){
        LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<SysRole>()
           .eq(SysRole::getDeleted,0).eq(SysRole::getStatus,0).orderByDesc(SysRole::getSort);
        List<SysRole> list = sysRoleService.list(query);
        return PageResult.success(list);
    }

    @ApiOperation(value="新增/更新角色", httpMethod = "POST")
    @ApiImplicitParam(name="role",value = "角色信息",paramType = "update",dataType = "SysRole")
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@Valid SysRole role, BindingResult result){
        if(result.hasErrors()){
            return Result.error(result.getFieldError().getDefaultMessage());
        }
        try {
            sysRoleService.saveOrUpdate(role);
           return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作出错啦!");
        }

    }

    @ApiOperation(value="根据ID删除角色", httpMethod = "POST")
    @ApiImplicitParam(name="id",value = "角色ID",paramType = "delete",dataType = "Integer")
    @PostMapping("/deleteById")
    public Result deleteById(Integer id){
        try {
            sysRoleService.removeById(id);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作出错啦");
        }
    }

    @ApiOperation(value="角色授权", httpMethod = "POST")
    @ApiImplicitParam(name="role",value = "角色信息",paramType = "update",dataType = "SysRole")
    @GetMapping("/authRole")
    public Result authRole(Integer id){
        if(id!=null && !"".equals(id)){
            List<MenuDTO> menuIds = sysRoleMenuService.findByRoleId(id);
            List<MenuTreeVo> menus = sysMenuService.getMenus(new SysMenu());
            List<AuthTreeVo> res=new ArrayList<AuthTreeVo>();
            menus.forEach(m ->{
                AuthTreeVo treeVo=new AuthTreeVo();
                treeVo.setId(m.getId());
                treeVo.setName(m.getMenuName()+" ");
                treeVo.setPId(m.getParentId());
                treeVo.setChecked(false);
                treeVo.setOpen(true);
                for (MenuDTO men : menuIds) {
                    if(m.getId()==men.getMenuId()){
                        treeVo.setChecked(true);
                    }
                }
                res.add(treeVo);
            });
          return  Result.success(res);
        }
        return Result.error();
    }

    @ApiOperation(value="根据角色ID查询菜单和资源", httpMethod = "GET")
    @ApiImplicitParam(name="roleId",value = "角色ID",paramType = "query",dataType = "Integer")
    @GetMapping("/roleList/{roleId}")
    public Result getRoleList(@PathVariable(name = "roleId") Integer roleId){
        // 获取菜单ID
        Result rourceById = sysRoleService.findRourceById(roleId);
        return rourceById;
    }

    @ApiOperation(value="根据角色ID查询角色名", httpMethod = "GET")
    @GetMapping("/getRoleName/{roleIds}")
    public Result getRoleName(@PathVariable("roleIds") String roleIds){

        System.out.println("用户角色："+roleIds);
        try {
            if(roleIds==null || "".equals(roleIds)) return Result.error("参数错误");
            Result result = sysRoleService.queryByRoleId(roleIds);
            return result;
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.error();
    }
}
